 /**
 * Description: 物资出库记录
 * @author:Hunter
 * @since:1.0.0
 *
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2018-04-08   Hunter       1.0.0     Initial
 */
package com.metro.paperless.app.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.metro.paperless.app.beans.vo.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.metro.core.annotation.BusinessDesc;
import com.metro.core.page.Page;
import com.metro.core.vo.JsonResult;
import com.metro.core.vo.QueryParams;
import com.metro.core.vo.ResultCode;
import com.metro.core.vo.inf.IResult;
import com.metro.paperless.app.service.inf.IAppMaterialsOutService;
import com.metro.paperless.app.service.inf.IAppOutDetailService;
import com.metro.paperless.biz.beans.vo.BizInsideOrg;
import com.metro.paperless.biz.service.inf.IBizInsideOrgService;
import com.metro.paperless.common.beans.constant.DicTypeEnum;
import com.metro.paperless.common.beans.constant.PropertiesEnum;
import com.metro.paperless.common.utils.CreateBarCodeUtils;
import com.metro.paperless.common.utils.DicUtil;
import com.metro.paperless.common.utils.IdGen;
import com.metro.paperless.common.utils.UserUtil;
import com.metro.paperless.sys.beans.vo.SysDeparment;
import com.metro.paperless.sys.beans.vo.SysUser;
import com.metro.paperless.sys.service.inf.ISysDeparmentService;
import com.metro.paperless.sys.service.inf.ISysUserService;
import com.metro.paperless.web.controller.BaseController;
import com.weslink.qsign.util.FtlUtil;

 /**
 * 物资出库记录<br>
 *
 * @author:Hunter
 * @since:1.0.0
 * @version [1.0.0, 2018-04-08]
 */
@Controller
@RequestMapping("/appMaterialsOut")
public class AppMaterialsOutController extends BaseController {
    //菜单编码
    private static final String menuCode = "APP_MATERIALS_OUT";
    //模块描述
    private static final String MODULE_DESC = "物资出库记录";
    @Autowired
    private IAppMaterialsOutService appmaterialsoutService;
    @Autowired
    private IBizInsideOrgService bizInsideOrgService;
    @Autowired
    private ISysDeparmentService deparmentService;
     @Autowired
     private IAppOutDetailService outDetailService;
    @Autowired
    private ISysUserService userService;

    @Override
    protected String getViewDir() {
        return "app/matout/";
    }

    /**
     * 去查询物资出库记录
     *
     * @param appmaterialsout 物资出库记录页面表单对象
     * @param page 分页配置
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "查询物资出库记录列表")
    @RequiresPermissions(menuCode + ":view")
    @SuppressWarnings("all")
    @RequestMapping(value = "list", method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView list(AppMaterialsOut appmaterialsout) {
        ModelAndView mav = new ModelAndView();
        try {
            mav.addObject("orgLists", DicUtil.getLabelValueList(DicTypeEnum.INSIDE_ORG_HIDDEN));
            mav.addObject("outLists", DicUtil.getLabelValueList(DicTypeEnum.OUTSIDE_ORG_HIDDEN));
            mav.addObject("outLists", DicUtil.getLabelValueList(DicTypeEnum.OUTSIDE_ORG_HIDDEN));
            mav.addObject("outStatus",DicUtil.getLabelValueList(DicTypeEnum.OUT_STATUS));
            mav.addObject("orgType","1");
            mav.addObject("searchEntity", appmaterialsout);
            mav.setViewName(getView("appmaterialsout_list"));
        } catch (Exception ex) {
            log.error("查询物资出库记录出错", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    }

    /**
     * 查询物资出库记录
     *
     * @param appmaterialsout 物资出库记录页面表单对象
     * @param page 分页配置
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "查询物资出库记录列表")
    @RequiresPermissions(menuCode + ":view")
    @SuppressWarnings("all")
    @RequestMapping(value = "dolist", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public JsonResult dolist(AppMaterialsOut appmaterialsout, Page page, QueryParams<AppMaterialsOut> queryParams) {
        JsonResult jr = new JsonResult();
        try {
            queryParams.setPaging(page);
            queryParams.setOrderColumn("a.id desc"); //添加排序
            queryParams.setEntity(appmaterialsout);
            PageInfo<AppMaterialsOut> pageInfo = appmaterialsoutService.queryForPage(queryParams);
            jr.setData(pageInfo);
            jr.setResult(ResultCode.SUCCESS);
        } catch (Exception ex){
            log.error("查询物资出库记录出错",ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }

    /**
     * 去新增物资出库记录
     *
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去新增物资出库记录")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "create")
    public ModelAndView createForm(Model model, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();
        //生成随机编号
        //编号生成规则为OS+年+月+日+四位随机数  即 OS+18+03+04+1234（不可编辑、唯一)
        String shortCode = "OS" + IdGen.getBarCode();
        //生成条码
        String barCodeImg = CreateBarCodeUtils.generateBaseMsg(shortCode);
        mav.addObject("barCode", shortCode);
        mav.addObject("barCodeImg", barCodeImg);
        SysUser user = userService.getById(UserUtil.getCurrUser().getUserId());
        SysDeparment deparment = deparmentService.getById(user.getDepartmentId());
        mav.addObject("deparment", deparment);
        AppMaterialsOut entity = new AppMaterialsOut();
        entity.setOrgType("1");
        mav.addObject("entity",entity);
        mav.addObject("user", user);
        try {
            initCreateOrUpdateFrom(mav, "create");
        } catch (Exception ex) {
            log.error("去新增物资出库记录出错", ex);
            mav.addObject("ex", ex);
            mav.setViewName("/commons/error/error");
        }
        return mav;
    }

    /**
     * 初始化新增修改物资出库记录所需参数
     * @author Hunter
     */
    private void initCreateOrUpdateFrom(ModelAndView mav, String action){
        mav.addObject("outStatuss", DicUtil.getLabelValueList(DicTypeEnum.OUT_STATUS));
        mav.addObject("orgTypes",DicUtil.getLabelValueList(DicTypeEnum.ORG_TYPE));
        mav.addObject("orgLists", DicUtil.getLabelValueList(DicTypeEnum.INSIDE_ORG_HIDDEN));
        mav.addObject("outLists", DicUtil.getLabelValueList(DicTypeEnum.OUTSIDE_ORG_HIDDEN));
        mav.addObject("action", action);
        mav.setViewName(getView("appmaterialsout_draft_form"));
    }


     /**
      * 去出库单展示页，准备签署
      *
      * @return 结果视图
      * @author Hunter
      * @since [1.0.0]
      * @version [1.0.0, 2018-04-10]
      */
     @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去出库单展示页，准备签署")
     @RequiresPermissions(menuCode + ":add")
     @RequestMapping(value = "outSign/{outId}")
     public ModelAndView outSignForm(Model model, HttpServletRequest request,@PathVariable String outId){
         ModelAndView mav = new ModelAndView();
         try {
             Map<String,String> resuleMap = createContract(outId);
             mav.addObject("content",resuleMap);

             Map redoMap= new HashMap();
             redoMap.put("cmd","redo");
             redoMap.put("seq_id",outId);
             String redo = JSONObject.toJSONString(redoMap);
             mav.addObject("redo",redo);

             Map homeMap= new HashMap();
             homeMap.put("cmd","home");
             homeMap.put("seq_id",outId);
             String home = JSONObject.toJSONString(homeMap);
             mav.addObject("home",home);

             Map getMap= new HashMap(); //获取图片
             getMap.put("cmd","get");
             getMap.put("seq_id",outId);
             String get = JSONObject.toJSONString(getMap);
             mav.addObject("get",get);

             Map cancelMap= new HashMap(); //取消
             cancelMap.put("cmd","cancel");
             cancelMap.put("seq_id",outId);
             String cancel = JSONObject.toJSONString(cancelMap);
             model.addAttribute("cancel",cancel);

             //出库物资
             List<AppOutDetail> appOutDetailList = outDetailService.queryListByOutId(Long.valueOf(outId));
             //查询物资出库记录
             AppMaterialsOut entity = appmaterialsoutService.getById(Long.valueOf(outId));

             String barCodeImg = CreateBarCodeUtils.generateBaseMsg(entity.getOutCode());

             mav.addObject("entity",entity);
             mav.addObject("barCodeImg", "data:image/png;base64,"+barCodeImg);
             String port = PropertiesEnum.getPropertyValue(PropertiesEnum.PAD_PATHPORT);
             mav.addObject("port",port);
             mav.addObject("appOutDetailList",appOutDetailList);
             mav.setViewName(getView("appmaterialsout_sign"));
         } catch (Exception ex) {
             log.error("去出库单展示页，准备签署", ex);
             mav.addObject("ex", ex);
             mav.setViewName("/commons/error/error");
         }
         return mav;
     }
     
     @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "物资出库单打印")
//   @RequiresPermissions(menuCode + ":add")
   @RequestMapping(value = "outPrint/{outId}")
   public ModelAndView outPrint(Model model, HttpServletRequest request,@PathVariable String outId){
   	ModelAndView mav = new ModelAndView();
   	try{
   	//出库物资
        List<AppOutDetail> appOutDetailList = outDetailService.queryListByOutId(Long.valueOf(outId));
        //查询物资出库记录
        AppMaterialsOut entity = appmaterialsoutService.getById(Long.valueOf(outId));

        String barCodeImg = CreateBarCodeUtils.generateBaseMsg(entity.getOutCode());

        mav.addObject("entity",entity);
        mav.addObject("barCodeImg", "data:image/png;base64,"+barCodeImg);
        String port = PropertiesEnum.getPropertyValue(PropertiesEnum.PAD_PATHPORT);
        mav.addObject("port",port);
        mav.addObject("appOutDetailList",appOutDetailList);
        mav.setViewName(getView("appmaterialsout_print"));
   	}catch(Exception ex){
   		log.error("物资出库单打印失败", ex);
        mav.addObject("ex", ex);
        mav.setViewName("/commons/error/error");
   	}
   	return mav;
   } 
     
     
     @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "物资出库单查看")
//   @RequiresPermissions(menuCode + ":add")
   @RequestMapping(value = "outPrintSigned/{outId}")
   public ModelAndView outPrintSigned(Model model, HttpServletRequest request,@PathVariable String outId){
   	ModelAndView mav = new ModelAndView();
   	try{
   	//出库物资
        List<AppOutDetail> appOutDetailList = outDetailService.queryListByOutId(Long.valueOf(outId));
        //查询物资出库记录
        AppMaterialsOut entity = appmaterialsoutService.getById(Long.valueOf(outId));

        String barCodeImg = CreateBarCodeUtils.generateBaseMsg(entity.getOutCode());

        mav.addObject("entity",entity);
        mav.addObject("barCodeImg", "data:image/png;base64,"+barCodeImg);
        String port = PropertiesEnum.getPropertyValue(PropertiesEnum.PAD_PATHPORT);
        mav.addObject("port",port);
        mav.addObject("appOutDetailList",appOutDetailList);
        mav.setViewName(getView("appmaterialsout_print_signed"));
   	}catch(Exception ex){
   		log.error("物资出库单查看失败", ex);
        mav.addObject("ex", ex);
        mav.setViewName("/commons/error/error");
   	}
   	return mav;
   } 

    /**
     * 新增物资出库记录
     *
     * @param entity 物资出库记录页面表单对象
     * @param request 请求对象
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "新增物资出库记录")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "save", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult saveAppMaterialsOut(AppOutDetailForm itemOut, AppMaterialsOut entity, HttpServletRequest request) {
        JsonResult jr = new JsonResult();
        try {
            List<AppMaterialsOut> list = appmaterialsoutService.queryForList(entity);
            if(list == null || list.size()<1 ){
                if(StringUtil.isBlank(entity.getOutTitle())){
                    String title = entity.getOrgName()+ itemOut.getItemOutEntity().get(0).getMaterialsName()+"等物资出库记录";
                    entity.setOutTitle(title);
                }
                jr = appmaterialsoutService.save(itemOut, entity); //保存出库记录和出库明细
                //保存完成后生成未签署的入库单
                String barCodeImg = CreateBarCodeUtils.generateBaseMsg(entity.getOutCode());
                Map<String, Object> data=new HashMap<>();
                data.put("matOutList", itemOut.getItemOutEntity());
                data.put("entity",entity);
                data.put("barCodeImg", "data:image/png;base64,"+barCodeImg);
                String rootDir = PropertiesEnum.getPropertyValue(PropertiesEnum.FILE_UPLOAD_ROOT);
                FtlUtil.tempalteToFile("out.ftl", data, rootDir+"/"+entity.getIdStr()+".pdf");

                Long outId  = (Long) jr.getData();
                jr.setResult(jr);
                jr.setData(outId);
            }else{
                jr.setResult(ResultCode.ERROR);
                jr.setMsg("当前出库单已保存");
            }
            log.debug("新增物资出库记录成功【{}】", entity);
        } catch (Exception ex) {
            log.error("新增物资出库记录出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }

    /**
     * 删除物资出库记录
     *
     * @param id 物资出库记录页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "删除物资出库记录")
    @RequiresPermissions(menuCode + ":delete")
    @RequestMapping(value = "delete/{id}", method = { RequestMethod.DELETE })
    @ResponseBody
    public JsonResult delete(@PathVariable String id, HttpServletRequest request){
        JsonResult jr = new JsonResult();
        try {
            log.debug("删除物资出库记录id={}",id);
            IResult codeMsg = appmaterialsoutService.deleteByIds(id);
            jr.setResult(codeMsg);
        } catch (Exception ex) {
            log.error("删除物资出库记录出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }

    /**
     * 去修改物资出库记录
     *
     * @param id 物资出库记录页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去修改物资出库记录")
    @RequiresPermissions(menuCode + ":edit")
    @RequestMapping(value = "edit/{id}", method = { RequestMethod.GET})
    public ModelAndView updateForm(@PathVariable Long id, HttpServletRequest request){
        ModelAndView mav = new ModelAndView();
        try {
            // 查询物资出库记录
            AppMaterialsOut entity = appmaterialsoutService.getById(id);
            // 根据借出单号获取出库明细
            List<AppOutDetail> list = outDetailService.queryListByOutId(id);
            String barCodeImg = CreateBarCodeUtils.generateBaseMsg(entity.getOutCode());

            mav.addObject("barCode", entity.getOutCode());
            mav.addObject("barCodeImg", barCodeImg);

            List<BizInsideOrg> orgList = bizInsideOrgService.queryForList(new BizInsideOrg());
            mav.addObject("orgList", orgList);

            SysUser user = userService.getById(UserUtil.getCurrUser().getUserId());
            SysDeparment deparment = deparmentService.getById(user.getDepartmentId());
            mav.addObject("deparment", deparment);
            mav.addObject("user", user);

            mav.addObject("appOutDetailList", list);
            mav.addObject("entity", entity);
            initCreateOrUpdateFrom(mav,"edit");
        } catch (Exception ex) {
            log.error("去修改物资出库记录", ex);
            mav.setView(new RedirectView("list"));
        }
        return mav;
    }

     /**
      * 签署成功保存文件
      * @param entity
      * @param request
      * @return
      */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "确认物资出库")
    @RequiresPermissions(menuCode + ":add")
    @RequestMapping(value = "commitOut", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult commitOut(AppMaterialsOut entity,String signName, HttpServletRequest request) {
        JsonResult jr = new JsonResult();
        try {
            Map<String,Object> data = new HashMap<>();

            String id = entity.getIdStr();
            //出库物资
            List<AppOutDetail>  appOutDetailList = outDetailService.queryListByOutId(Long.valueOf(id));
            // 查询物资出库记录
            entity = appmaterialsoutService.getById(Long.valueOf(id));
            //操作数据
            entity.setOutStatus("2");
            entity.setOutTime(new Date());
            entity.setSignName(signName);

            String barCodeImg = CreateBarCodeUtils.generateBaseMsg(entity.getOutCode());
            data.put("signname",signName);
            data.put("matOutList", appOutDetailList);
            data.put("entity",entity);
            data.put("barCodeImg", "data:image/png;base64,"+barCodeImg);
            String rootDir = PropertiesEnum.getPropertyValue(PropertiesEnum.FILE_UPLOAD_ROOT);
            FtlUtil.tempalteToFile("out.ftl", data, rootDir+"/"+entity.getIdStr()+"-signed.pdf");

            jr.setResult(appmaterialsoutService.update(entity,"commint"));

            log.debug("物资出库成功【{}】", entity);
        } catch (Exception ex) {
            log.error("物资出库出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
     }
    /**
     * 修改物资出库记录
     *
     * @param entity 物资出库记录页面表单对象
     * @param request 请求对象
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "修改物资出库记录")
    @RequiresPermissions(menuCode + ":edit")
    @RequestMapping(value = "update", method = { RequestMethod.POST})
    @ResponseBody
    public JsonResult updateAppMaterialsOut(AppOutDetailForm itemEntity,AppMaterialsOut entity, HttpServletRequest request) {
        JsonResult jr = new JsonResult();
        try {
            IResult res = appmaterialsoutService.update(itemEntity,entity);

            String barCodeImg = CreateBarCodeUtils.generateBaseMsg(entity.getOutCode());
            Map<String, Object> data=new HashMap<>();
            data.put("matOutList", itemEntity.getItemOutEntity());
            data.put("entity",entity);
            data.put("barCodeImg", "data:image/png;base64,"+barCodeImg);
            String rootDir = PropertiesEnum.getPropertyValue(PropertiesEnum.FILE_UPLOAD_ROOT);
            FtlUtil.tempalteToFile("out.ftl", data, rootDir+"/"+entity.getIdStr()+".pdf");
            jr.setResult(res);
            jr.setData(entity.getId());
            log.debug("修改物资出库记录成功【{}】", entity);
        } catch (Exception ex) {
            log.error("修改物资出库记录出错", ex);
            jr.setResult(ResultCode.ERROR);
        }
        return jr;
    }

     /**
      * 作废物资入库记录
      *
      * @param entity 物资入库记录页面表单对象
      * @param request 请求对象
      * @return 结果视图
      * @author Hunter
      * @since [1.0.0]
      * @version [1.0.0, 2018-04-08]
      */
     @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "修改物资入库记录")
     @RequiresPermissions(menuCode + ":edit")
     @RequestMapping(value = "invalid", method = { RequestMethod.POST})
     @ResponseBody
     public JsonResult invalidAppMaterialsIn(AppMaterialsOut entity, HttpServletRequest request) {
         JsonResult jr = new JsonResult();
         try {
             Map<String,Object> data = new HashMap<>();
             String id = entity.getIdStr();
             String invalidRemark = entity.getInvalidRemark();
             //入库物资
             List<AppOutDetail>  appOutDetailList = outDetailService.queryListByOutId(Long.valueOf(id));
             // 查询物资入库记录
             entity = appmaterialsoutService.getById(Long.valueOf(id));
             //操作数据
             entity.setOutStatus("3");//作废
             entity.setOutTime(new Date());//作废时间
             entity.setInvalidRemark(invalidRemark);//作废原因

             data.put("signname",entity.getSignName());
             data.put("matOutList", appOutDetailList);
             data.put("entity",entity);
             data.put("barCodeImg", "data:image/png;base64,"+ CreateBarCodeUtils.generateBaseMsg(entity.getOutCode()));
             String rootDir = PropertiesEnum.getPropertyValue(PropertiesEnum.FILE_UPLOAD_ROOT);
             FtlUtil.tempalteToFile("out.ftl", data, rootDir+"/"+entity.getIdStr()+"-invalid.pdf");

             IResult res = appmaterialsoutService.update(entity,"invalid");
             jr.setResult(res);
             jr.setData(entity.getId());
             log.debug("作废物资入库记录成功【{}】", entity);
         } catch (Exception ex) {
             log.error("作废物资入库记录出错", ex);
             jr.setResult(ResultCode.ERROR);
         }
         return jr;
     }

    /**
     * 去查看物资出库记录
     *
     * @param id 物资出库记录页面表单对象唯一标识
     * @return 结果视图
     * @author Hunter
     * @since [1.0.0]
     * @version [1.0.0, 2018-04-08]
     */
    @BusinessDesc(ModuleDesc = MODULE_DESC, MethodDesc = "去查看物资出库记录详情")
    @RequiresPermissions(menuCode + ":view")
    @RequestMapping(value = "info/{id}", method = { RequestMethod.GET })
    public ModelAndView info(@PathVariable Long id) {
        ModelAndView mav= new ModelAndView();
        try {
            mav.addObject("outId",id);
            mav.setViewName(getView("appmaterialsout_info"));
        } catch (Exception ex) {
            log.error("查看物资出库记录出错", ex);
        }
        return mav;
    }



}
